//实现一个循环队列
class Queue{
    int size;
    int [] arr=new int[10];
    int head=0;
    int tail=0;
    Object lock=new Object();
    //入队列
    public  void push(int value) throws InterruptedException {
        //判定数组是否满
        synchronized (lock) {
            if (size >= arr.length) {
                //此时处于阻塞
                lock.wait();
            }
            arr[tail] = value;
            tail++;
            size++;
            if (tail >= arr.length) {
                tail = 0;
            }
            lock.notify();
        }
    }
    //出队列
    public  Integer take() throws InterruptedException {
        //判定队列是否为空
        synchronized (lock) {
            if (size == 0) {
                //此时处于阻塞
                lock.wait();
            }
            int val = arr[head];
            head++;
            size--;
            if (head >= arr.length) {
                head = 0;
            }
            lock.notify();
            return val;
        }
    }

}
public class BlockingQueue {
    public static void main(String[] args) {
        Queue queue=new Queue();
        Thread t1=new Thread(()->{
            int num=0;
          while(true){
                try {
                    queue.push(num);
                    System.out.println("生产了"+num);
                    num++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2=new Thread(()->{
            while(true){
                try {
                    int num= queue.take();
                    System.out.println("消费了"+num);
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
//    public static void main1(String[] args) {
//        Queue queue=new Queue();
//        queue.push(1);
//        queue.push(2);
//        queue.push(3);
//        queue.push(4);
//        System.out.println(queue.take());
//        System.out.println(queue.take());
//        System.out.println(queue.take());
//        System.out.println(queue.take());
//    }
}
